package com.jp.knowledge.http;

import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 528787067@qq.com on 2017/1/9.
 */

public class HttpGet {
    public static void httpGetData(final int requestCode, final String url, final HttpGetCallback callback){
        Observable.OnSubscribe<String> onSubscribe = new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                OkHttpClient mHttpClient = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(url)
                        .build();
                try {
                    Response response = mHttpClient.newCall(request).execute();
                    subscriber.onNext(response.body().string());
                } catch (IOException e) {
                    subscriber.onError(new Throwable(e));
                }
            }
        };
        Subscriber<String> subscriber = new Subscriber<String>(){
            @Override
            public void onCompleted() {
                callback.onCompleted(requestCode);
            }
            @Override
            public void onError(Throwable e) {
                callback.onError(requestCode, e);
            }
            @Override
            public void onNext(String data) {
                callback.onNext(requestCode, data);
            }
        };
        Observable.create(onSubscribe)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }

    public interface HttpGetCallback{
        void onCompleted(int requestCode);
        void onError(int requestCode, Throwable e);
        void onNext(int requestCode, String data);
    }
}
